<template>
  <div style="padding: 10px 18px;min-height: 700px">
    <div class="header" style="height: 130px;padding: 30px 0 10px;width: 100%;">
      <div style="float: left;width: 40%;text-align: center">
        <div style="text-align: center;position:relative;">
          <div class="icon-wrapper" @click="clickInput">
            <img :src="fileData || imgSrc || require('../assets/default.jpg')" style="width: 65px;border-radius: 50%;">
            <div style="text-align: center">
              <span>更换头像</span>
            </div>
            <input type="file" class="hide" @change="changeImage" ref="file"/>
          </div>

        </div>
        <div style="font-size: 13px;" @click="changeName"><span class="iconfont icon-xiugai"></span> {{name}}</div>
      </div>
      <div style="float: left;width: 60%;">
        <button @click="pickTemplate" class="choose-button" style="width: 100%;height: 80px;">
          <span class="iconfont icon-fuzhi" style="font-size: 22px;"></span>
          选择更多模板
        </button>
      </div>
    </div>
    <AudioItem @selectOne="selectOne" :item="item" :items="items" :pojos="pojos" v-for="(item,index) in items" :index="index" :key="item.id"></AudioItem>
    <div class="add-audio-item" v-if="items.length >= 2">
      <a class="add-audio-item-button" @click.prevent.stop="addOne">添加编辑框</a>
    </div>
    <PickTemplate @use="use" :templates="templates" v-if="showTemplates" @close="showTemplates = false;"></PickTemplate>
    <div>
      <button class="preview-button" @click="save">
        <span class="iconfont icon-bofang"></span>
        &nbsp;预览
      </button>
    </div>

    <div class="cropper-container" v-if="showCropper">
      <div class="cropper-content">
        <vueCropper
          ref="cropper"
          :img="option.src"
          :autoCrop="option.autoCrop"
          :canMove="true"
          :centerBox="true"
          :fixedBox="true"
          :fixed="true"
          :outputSize="option.size"
          :outputType="option.outputType"
        ></vueCropper>
      </div>
      <div class="cropper-footer">
        <span @click="showCropper = false;">取消</span>
        <span @click="startCrop">确定</span>
      </div>

    </div>

    <div id="audioBox" class="audio-hide"></div>

  </div>
</template>

<script>
import axios from 'axios'
import '../assets/font/iconfont/iconfont.css'
import { MessageBox } from 'mint-ui'
import { VueCropper } from 'vue-cropper'
import AudioItem from './EditAudio/components/AudioItem'
import PickTemplate from './EditAudio/components/PickTemplate'
import utils from '../utils'
// import Share from './Share'

// const openid = 'oJjc50xb8v2Ifd4pd2f4EkeYgkuM'

export default {
  name: 'edit-audio',
  data () {
    return {
      id: this.$route.params.id,
      type: this.$route.params.type,
      showTemplates: false,
      items: [],
      name: '未填写',
      showCropper: false,
      templates: [],
      pojos: [],
      imgSrc: '',
      fileData: null,
      option: {
        img: '',
        size: 150,
        autoCrop: true,
        outputType: 'jpg'
      },
      openid: '',
      port: ''
    }
  },
  mounted () {
    if (process.env.NODE_ENV !== 'development') {
      let local = window.location.href
      let appid = 'wx7e2328fe819d9692'
      let code = utils.urlParam('code')
      if (code === null || code === '') {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
      } else {
        this.getOpenId(code)
      }
    } else {
      this.openid = 'oJjc50xb8v2Ifd4pd2f4EkeYgkuM'
    }
  },
  async created () {
    const {page} = (await this.$http.post('/biaobeihy/content/findAll?page=1&count=13')).data
    this.templates = page.list
    const {pojoList} = (await this.$http.get('/biaobeihy/voiceChange/findAll')).data
    this.pojos = pojoList

    if (this.id) {
      const {
        headimgUrl,
        nickname,
        timeSpanList,
        port,
        contentList} = (await this.$http.post('/biaobeihy/hy/findOneById', {
        id: this.id
      })).data
      this.imgSrc = headimgUrl
      this.name = nickname
      this.port = port
      const findP = this.pojos.filter(pojo => ('' + pojo.port) === port)
      this.items = contentList.map((content, index) => {
        return {
          id: Math.random(),
          text: content,
          name: findP.length ? findP[0].name : pojoList[0].name,
          time: timeSpanList[index] || 5,
          pojoId: port
        }
      })
    } else {

      this.items = this.templates[0].contentList.map((content) => {
        return {
          id: Math.random(),
          text: content,
          name: this.templates[0].nickname,
          time: 5,
          pojoId: this.templates[0].port
        }
      })
      this.port = this.templates[0].port
      this.imgSrc = this.templates[0].url
    }
  },
  methods: {
    save () {
      if (!this.imgSrc && !this.fileData) return alert('头像未上传！')
      if (!this.name) return alert('昵称未填写！')

      if (this.items.filter(item => !item.text).length > 0) return alert('有未填写的编辑框')
      const data = {
        openid: this.openid,
        nickname: this.name,
        port: this.port,
        contentList: this.items.map(value => value.text),
        timeSpanList: this.items.map(v => v.time),
        voiceUrlList: this.items.map(value =>
            (!['8001', '8040'].includes(this.port + '') ? 'http://39.104.162.93:' : 'http://1.203.80.138:') + this.port +
          '/tts?user_id=speech&domain=1&language=zh&rate=8&speed=5&volume=5&voice_name=1&text=' +
          value.text
        ),
        fileData: this.fileData,
        headimgUrl: this.imgSrc,
        type: 'png'
      }
      this.$store.dispatch('setProgress', 50)
      axios.create().post('/biaobeihy/userContent/saveBase', data, {
        // headers: {
        //   'Content-Type': 'multipart/form-data'
        // }
      }).then(response => {
        this.$store.dispatch('setProgress', 50)
        console.log(response)
        this.$router.push('/connected/preview/' + response.data.id)
      })
    },
    getOpenId (code) {
      this.$http.post('/biaobeihy/wxUser/getOpenid', {
        code: code
      }).then(response => {
        console.log(response)
        this.openid = response.data.openId
      })
    },
    pickTemplate () {
      this.showTemplates = true
    },
    addOne () {
      this.items.push({
        id: Math.random(),
        time: 5,
        text: ''
      })
    },
    clickInput () {
      this.$refs.file.click()
    },
    changeImage (e) {
      const file = e.target.files[0]

      if (!file.type.includes('image/')) {
        alert('Please select an image file')
        return
      }

      if (typeof FileReader === 'function') {
        const reader = new FileReader()

        reader.onload = (event) => {
          // rebuild cropperjs with the updated source
          this.option.src = event.target.result
          console.log(file.type)
          this.showCropper = true
        }

        reader.readAsDataURL(file)
      } else {
        alert('Sorry, FileReader API not supported')
      }
    },
    changeName () {
      const self = this
      MessageBox.prompt('改个名字').then(({ value }) => {
        self.name = value
      })
    },
    startCrop () {
      this.$refs.cropper.getCropData((data) => {
        this.fileData = data
        this.showCropper = false
        this.$refs.file.value = ''
      })
    },
    use (id) {
      this.$http.post('/biaobeihy/content/use', {
        id: id
      }, {noInterceptor: true})
      const template = this.templates.find(template => template.id === id)
      this.port = template.port
      this.imgSrc = template.url
      this.fileData = null
      this.name = template.nickname
      const result = []
      const content = template.contentList
      for (let i = 0; i < content.length; i += 2) {
        result.push({
          id: Math.random(),
          text: content[i],
          time: content[i + 1] || 0,
          name: this.pojos.find(pojo => pojo.port === template.port).name,
          pojoId: template.port
        })
      }

      this.items = result
      this.showTemplates = false
    },
    selectOne (pojo) {
      this.port = pojo.port
    }
  },
  components: {
    AudioItem,
    PickTemplate,
    VueCropper
  }
}
</script>

<style scoped lang="less" rel="stylesheet/less">
.choose-button {
  background: -webkit-linear-gradient(left, #20BDFF , #7F00FF); /* Safari 5.1 - 6.0 */
  background: -o-linear-gradient(right, #20BDFF , #7F00FF); /* Opera 11.1 - 12.0 */
  background: -moz-linear-gradient(right, #20BDFF , #7F00FF); /* Firefox 3.6 - 15 */
  background: linear-gradient(to right, #20BDFF , #7F00FF); /* 标准的语法 */
  border-radius:6px;/*适配所有浏览器*/
  transition: box-shadow .3s;
  border: 1px solid #C6C4C4;
  outline: none;
  font-size: 22px;
  color: #fff;
  white-space: nowrap;
}

.header {
  clear: both;
  box-sizing: border-box;
}
.audio-item {
  width: 100%;
  margin-top: 15px;
  height: 70px;
}
.choose-button-small {
  background: -webkit-linear-gradient(left, #20BDFF , #7F00FF); /* Safari 5.1 - 6.0 */
  background: -o-linear-gradient(right, #20BDFF , #7F00FF); /* Opera 11.1 - 12.0 */
  background: -moz-linear-gradient(right, #20BDFF , #7F00FF); /* Firefox 3.6 - 15 */
  background: linear-gradient(to right, #20BDFF , #7F00FF); /* 标准的语法 */
  border-radius:6px;/*适配所有浏览器*/
  transition: box-shadow .3s;
  border: 1px solid #C6C4C4;
  outline: none;
  font-size: 16px;
  color: #fff;
  white-space: nowrap;
}
.add-audio-item {
  margin-top: 15px;
  margin-bottom: 20px;
}
.add-audio-item-button {
  color: #727AF6;
}
.preview-button {
  margin-top: 20px;
  background: #707FF6;
  border-radius:6px;/*适配所有浏览器*/
  transition: box-shadow .3s;
  border: 0px;
  outline: none;
  font-size: 16px;
  color: #fff;
  height: 45px;
  width: 100%;
}

  .icon-wrapper {
    position: relative;
    width: 65px;
    height: 65px;
    border-radius: 50%;
    overflow: hidden;
    display: inline-block;
    box-shadow: 0 3px 3px rgba(0, 0, 0, .3);

    > img {
      width: 65px;
      height: 65px;
      border-radius: 50%;
    }

    > div {
      font-size: 12px;
      position: absolute;
      bottom: 3px;
      padding: 5px 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, .5);
      color: #fff;

      > span {
        display: inline-block;
        transform: scale(.8);
      }
    }
  }

  .hide {
    display: none;
  }

  .cropper-container {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, .5);
  }

  .cropper-content {
    width: 200px;
    height: 200px;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%, -50%, 0);
    z-index: 10;
  }

  .cropper-footer {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    z-index: 100;
    display: flex;

    > span {
      color: #fff;
      flex: 1;
      padding: 10px;
      text-align: center;
    }
  }

  .audio-hide {
    display: none;
  }
</style>
